﻿//------------------------------------------------------------------------------
// System Name:    Customer Service Platform
// Component:      CCS Advance Search
// Modify By:      Leo Ren (leoren@wicresoft.com)
// Modify Date:    2011-1-28
//------------------------------------------------------------------------------

using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Web;
using System.Web.SessionState;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Linq;
using ASBCC.Business;
using BEGDC.CC.BL.Common;
using BEGDC.CC.BL.Common.Query;
using BEGDC.CC.BL.UserManagement;
using BEGDC.CC.BL.Workflow;
using BEGDC.CC.Entity;
using BEGDC.CC.Web.UserControls;
using BEGDC.Utility.Castle;
using BEGDC.Utility.ExceptionManagement;
using NetBpm.Util.Client;
using NetBpm.Workflow.Execution;
using NetBpm.Workflow.Execution.EComp;

namespace BEGDC.CC.Web.Workflow
{
    /// <summary>
    /// Summary description for SearchChange.
    /// </summary>
    public class AdvancedSearch : System.Web.UI.Page
    {
        private const string SEARCH_CR = "CR";
        private const string SEARCH_CV = "CV";
        private const string SEARCH_EV = "EV";
        private const string SEARCH_CO = "CO";
        private const string SEARCH_AP = "AP";
        private const string SEARCH_OCR = "OCR";
        private const string SEARCH_OCV = "OCV";
        private const string SEARCH_EBD = "EBD";
        private const string SEARCH_ESC = "ESC";
        //private const string SEARCH_EBDCR = "EBDCR";
        //private const string SEARCH_ESCCR = "ESCCR";
        private const string SEARCH_EBDCV = "EBDCV";
        private const string SEARCH_ESCCV = "ESCCV";

        private string searchFlowType = string.Empty;

        /// <summary>
        /// 
        /// </summary>
        private int _SearchID
        {
            get
            {
                if (Session["_SearchID"] == null) return 0;

                return Convert.ToInt32(Session["_SearchID"]);
            }
            set { Session["_SearchID"] = value; }
        }

        /// <summary>
        /// 
        /// </summary>
        private string _SearchType
        {
            get
            {
                if (Session["SearchType"] == null) return SEARCH_CR;

                return (string)Session["SearchType"];
            }
            set { Session["SearchType"] = value; }
        }

        /// <summary>
        /// 
        /// </summary>
        private string _SearchSQL_Fields
        {
            get
            {
                if (Session["_SearchSQL_Fields"] == null) return string.Empty;

                return (string)Session["_SearchSQL_Fields"];
            }
            set { Session["_SearchSQL_Fields"] = value; }
        }

        /// <summary>
        /// 
        /// </summary>
        private string _SearchSQL_Condition
        {
            get
            {
                if (Session["_SearchSQL_Condition"] == null) return string.Empty;

                return (string)Session["_SearchSQL_Condition"];
            }
            set { Session["_SearchSQL_Condition"] = value; }
        }

        /// <summary>
        /// 
        /// </summary>
        private string _SearchSQL
        {
            get
            {
                if (Session["SearchSQL"] == null) return string.Empty;

                return (string)Session["SearchSQL"];
            }
            set { Session["SearchSQL"] = value; }
        }

        private SortManager _SortManager
        {
            get
            {
                if (ViewState["SortManager"] == null) return new SortManager();

                return (SortManager)ViewState["SortManager"];
            }
            set { ViewState["SortManager"] = value; }

        }

        private DataTable _SearchResult
        {
            get
            {
                if (Session["ChangeSearchResult"] == null) return null;

                else return (DataTable)Session["ChangeSearchResult"];
            }
            set
            {
                Session["ChangeSearchResult"] = value;
            }
        }

        private System.Collections.ArrayList _SearchFieldsKey
        {
            get
            {
                if (ViewState["_SearchFieldsKey"] == null) return null;

                else return (System.Collections.ArrayList)ViewState["_SearchFieldsKey"];
            }
            set
            {
                ViewState["_SearchFieldsKey"] = value;
            }
        }

        private System.Collections.Hashtable _SearchFields
        {
            get
            {
                if (ViewState["SearchFields"] == null) return null;

                else return (System.Collections.Hashtable)ViewState["SearchFields"];
            }
            set
            {
                ViewState["SearchFields"] = value;
            }
        }

        private BEGDC.CC.Entity.AdvancedSearch _SearchEntity
        {
            get
            {
                if (ViewState["SearchEntity"] == null) return null;

                else return ViewState["SearchEntity"] as BEGDC.CC.Entity.AdvancedSearch;
            }
            set
            {
                ViewState["SearchEntity"] = value;
            }
        }

        protected System.Web.UI.WebControls.TextBox txtTime1;
        protected System.Web.UI.WebControls.TextBox txtTime2;
        protected System.Web.UI.WebControls.TextBox txtTime3;

        protected System.Web.UI.WebControls.DropDownList ddlColumn3;
        protected System.Web.UI.WebControls.DropDownList ddlOperator3;
        protected System.Web.UI.WebControls.TextBox txtValue3;
        protected System.Web.UI.WebControls.DropDownList ddlColumn1;
        protected System.Web.UI.WebControls.DropDownList ddlOperator1;
        protected System.Web.UI.WebControls.DropDownList ddlColumn2;
        protected System.Web.UI.WebControls.DropDownList ddlOperator2;
        protected System.Web.UI.WebControls.TextBox txtValue2;
        protected System.Web.UI.WebControls.DropDownList ddlLogic2;
        protected System.Web.UI.WebControls.DropDownList ddlLogic1;
        protected System.Web.UI.WebControls.TextBox txtValue1;
        protected System.Web.UI.HtmlControls.HtmlTable tblSimpleSetting2;
        protected System.Web.UI.HtmlControls.HtmlGenericControl spnTotal;
        protected System.Web.UI.HtmlControls.HtmlGenericControl spnInfo;
        protected System.Web.UI.HtmlControls.HtmlInputHidden varAction;
        protected System.Web.UI.WebControls.DropDownList ddlStatus1;
        protected System.Web.UI.WebControls.DropDownList ddlStatus2;
        protected System.Web.UI.WebControls.DropDownList ddlStatus3;
        protected System.Web.UI.WebControls.Label lbGroup;
        protected System.Web.UI.WebControls.Label lbNoGroup;
        protected System.Web.UI.WebControls.ListBox TargetBox;
        protected System.Web.UI.WebControls.ImageButton btnRemove;
        protected System.Web.UI.WebControls.ImageButton btnRemoveAll;
        protected System.Web.UI.WebControls.ImageButton btnAdd;
        protected System.Web.UI.WebControls.ImageButton btnAddAll;
        protected System.Web.UI.WebControls.ListBox SourceBox;
        //protected System.Web.UI.WebControls.TextBox txtDisplayFields;
        protected System.Web.UI.WebControls.DataGrid dgTaskList;
        protected System.Web.UI.WebControls.Label lblRecordCount;
        protected System.Web.UI.WebControls.Label lblCurrentPageIndex;
        protected System.Web.UI.WebControls.Label lblPageCount;
        protected System.Web.UI.WebControls.ImageButton btnPageFirst;
        protected System.Web.UI.WebControls.ImageButton btnPagePrev;
        protected System.Web.UI.WebControls.ImageButton btnPageNext;
        protected System.Web.UI.WebControls.ImageButton btnPageLast;
        protected System.Web.UI.WebControls.TextBox txtPage;
        protected System.Web.UI.WebControls.ImageButton btnGotoPage;
        protected System.Web.UI.WebControls.Panel Panel1;
        protected System.Web.UI.HtmlControls.HtmlImage dtImg2;
        protected System.Web.UI.HtmlControls.HtmlImage dtImg1;
        protected System.Web.UI.HtmlControls.HtmlImage dtImg3;
        protected System.Web.UI.WebControls.Panel Panel2;
        protected System.Web.UI.WebControls.Label lblCostSum;
        protected System.Web.UI.WebControls.Button btnSearch;
        protected System.Web.UI.WebControls.Button btnExport;
        protected System.Web.UI.WebControls.Button btnSaveSearch;

        protected System.Web.UI.WebControls.DropDownList ddlProvince1;
        protected System.Web.UI.WebControls.DropDownList ddlProvince2;
        protected System.Web.UI.WebControls.DropDownList ddlProvince3;
        protected System.Web.UI.WebControls.DropDownList ddlCategory1;
        protected System.Web.UI.WebControls.DropDownList ddlCategory2;
        protected System.Web.UI.WebControls.DropDownList ddlCategory3;
        protected System.Web.UI.WebControls.DropDownList ddlCluster1;
        protected System.Web.UI.WebControls.DropDownList ddlCluster2;
        protected System.Web.UI.WebControls.DropDownList ddlCluster3;
        protected System.Web.UI.WebControls.DropDownList ddlExecutive1;
        protected System.Web.UI.WebControls.DropDownList ddlExecutive2;
        protected System.Web.UI.WebControls.DropDownList ddlExecutive3;
        //OCR EBDCR ESCCR
        protected System.Web.UI.HtmlControls.HtmlGenericControl OCRDiv;
        protected System.Web.UI.WebControls.RadioButtonList OCRRadioButtonList;
        //OCV EBDCV ESCCV
        protected System.Web.UI.HtmlControls.HtmlGenericControl OCVDiv;
        protected System.Web.UI.WebControls.RadioButtonList OCVRadioButtonList;

        private string SearchType()
        {
            //changed search type by selected
            string flowType = Request.QueryString["type"];

            if (this.OCRDiv.Visible)
            {
                //show OCR advance search
                if (this.OCRRadioButtonList.SelectedValue == WorkflowTypes.EBD)
                {
                    flowType = WorkflowTypes.EBD;
                }
                else if (this.OCRRadioButtonList.SelectedValue == WorkflowTypes.ESC)
                {
                    flowType = WorkflowTypes.ESC;
                }
                else if (this.OCRRadioButtonList.SelectedValue.ToLower() == "all")
                {
                    flowType = WorkflowTypes.AllOCR;
                }
                else
                {
                    flowType = WorkflowTypes.OCR;
                }
            }
            if (this.OCVDiv.Visible)
            {
                //show OCV advance search
                if (this.OCVRadioButtonList.SelectedValue == WorkflowTypes.EBDCV)
                {
                    flowType = WorkflowTypes.EBDCV;
                }
                else if (this.OCVRadioButtonList.SelectedValue == WorkflowTypes.ESCCV)
                {
                    flowType = WorkflowTypes.ESCCV;
                }
                else if (this.OCVRadioButtonList.SelectedValue.ToLower() == "all")
                {
                    flowType = WorkflowTypes.AllOCV;
                }
                else
                {
                    flowType = WorkflowTypes.OCV;
                }
            }
            return flowType;
        }

        private void ShowRadioButton()
        {
            string search = Request.QueryString["type"];

            if (search == WorkflowTypes.OCR)
            {
                this.OCRDiv.Visible = true;
                this.OCVDiv.Visible = false;
            }
            else if (search == WorkflowTypes.OCV)
            {
                this.OCRDiv.Visible = false;
                this.OCVDiv.Visible = true;
            }
            else
            {
                this.OCRDiv.Visible = false;
                this.OCVDiv.Visible = false;
            }
        }

        private void Page_Load(object sender, System.EventArgs e)
        {
            this.ShowRadioButton();

            this.searchFlowType = this.SearchType();

            if (!IsPostBack)
            {
                this.ddlColumn1.Attributes["onpropertychange"] = "OnSelectColumn();";
                this.ddlColumn2.Attributes["onselectindexchange"] = "OnSelectColumn();";
                this.ddlColumn2.Attributes["onselectindexchange"] = "OnSelectColumn();";

                string search = Request.QueryString["type"];
                string searchID = Request.QueryString["id"];
                if (searchID != null && searchID != string.Empty)
                    this._SearchID = Convert.ToInt32(searchID);
                else
                    this._SearchID = 0;

                if (search == null || search.Trim() == String.Empty) search = SEARCH_CR.ToString();

                InitSearch(search);

                this._SearchSQL = FetchSQL();

                this.btnSaveSearch.Attributes.Add("onclick", "javascript:showSaveForm();");
                //				if( this._SearchType != SEARCH_CR )
                //					DoSearch();
                this.Panel2.Visible = false;

                this.txtTime1.Attributes.Add("display", "none");
                this.txtTime2.Attributes.Add("display", "none");
                this.txtTime3.Attributes.Add("display", "none");
            }
            else
            {
                if (Page.Request.Form[0].IndexOf("dgTaskList") > -1)
                {
                    this.BindData(this._CurrentPageIndex);
                }

            }
        }

        #region Web Form Designer generated code
        override protected void OnInit(EventArgs e)
        {
            //
            // CODEGEN: This call is required by the ASP.NET Web Form Designer.
            //
            InitializeComponent();
            base.OnInit(e);
        }

        /// <summary>
        /// Required method for Designer support - do not modify
        /// the contents of this method with the code editor.
        /// </summary>
        private void InitializeComponent()
        {
            this.btnSearch.Click += new EventHandler(btnSearch_Click);
            this.btnExport.Click += new EventHandler(btnExport_Click);
            this.btnSaveSearch.Click += new EventHandler(btnSaveSearch_Click);

            this.btnRemove.Click += new System.Web.UI.ImageClickEventHandler(this.btnRemove_Click);
            this.btnRemoveAll.Click += new System.Web.UI.ImageClickEventHandler(this.btnRemoveAll_Click);
            this.btnAdd.Click += new System.Web.UI.ImageClickEventHandler(this.btnAdd_Click);
            this.btnAddAll.Click += new System.Web.UI.ImageClickEventHandler(this.btnAddAll_Click);
            this.dgTaskList.SortCommand += new System.Web.UI.WebControls.DataGridSortCommandEventHandler(this.dgTaskList_SortCommand);
            this.dgTaskList.ItemDataBound += new System.Web.UI.WebControls.DataGridItemEventHandler(this.dgTaskList_ItemDataBound);
            this.btnPageFirst.Click += new System.Web.UI.ImageClickEventHandler(this.btnPageFirst_Click);
            this.btnPagePrev.Click += new System.Web.UI.ImageClickEventHandler(this.btnPagePrev_Click);
            this.btnPageNext.Click += new System.Web.UI.ImageClickEventHandler(this.btnPageNext_Click);
            this.btnPageLast.Click += new System.Web.UI.ImageClickEventHandler(this.btnPageLast_Click);
            this.btnGotoPage.Click += new System.Web.UI.ImageClickEventHandler(this.btnGotoPage_Click);
            this.Load += new System.EventHandler(this.Page_Load);

        }

        #endregion

        //===================================== private methods ===============================		

        #region InitSearch

        private void InitSearch(string searchType)
        {
            BEGDC.CC.BL.AdvancedSearch.IAdvancedSearch iquery = AppContainer.Instance[ServiceConst.SearchService] as BEGDC.CC.BL.AdvancedSearch.IAdvancedSearch;

            if (this._SearchID > 0)
            {
                _SearchEntity = iquery.GetAdvancedSearch(this._SearchID);
                //this.txtDisplayFields.Text = "hide";

                //Order by 
                if (_SearchEntity.SearchSQL.IndexOf("order by") > -1)
                {
                    string field = _SearchEntity.SearchSQL.Substring(_SearchEntity.SearchSQL.IndexOf("order by") + 9);

                    SortManager sort = this._SortManager;

                    sort.DoSort(field.Substring(0, field.Length - 4).Trim(), field.Substring(field.Length - 4).Trim());

                    this._SortManager = sort;

                }

            }

            // Init search fields
            this._SearchType = searchType;


            this.GetSearchFields();
            string roles = ((CCPrincipal)HttpContext.Current.User).Roles;
            if (roles.IndexOf(",") > 0)
                roles = roles.Substring(roles.IndexOf(",") + 1);

            foreach (string fieldname in this._SearchFieldsKey)
            {
                SearchField field = this._SearchFields[fieldname] as SearchField;

                //if (field._description.ToLower() != "actual" || roles.ToLower() != "'ocoapplicant'")
                if (!field._description.ToLower().Contains("actual") || roles.ToLower() != "'ocoapplicant'")
                {
                    if (field._issearch)
                    {
                        this.ddlColumn1.Items.Add(new ListItem(field._description.Replace("<br/>", ""), field._name));
                        this.ddlColumn2.Items.Add(new ListItem(field._description.Replace("<br/>", ""), field._name));
                        this.ddlColumn3.Items.Add(new ListItem(field._description.Replace("<br/>", ""), field._name));
                    }
                }
                if (this._SearchID == 0)
                {
                    if (field._isdefault)
                    {
                        TargetBox.Items.Add(new ListItem(field._description.Replace("<br/>", ""), field._name));
                    }
                    else
                    {
                        //<--joan 2008/8/30
                        if (roles.ToLower() != "'ocoapplicant'" && field._description.ToLower().Contains("actual"))
                            TargetBox.Items.Add(new ListItem(field._description.Replace("<br/>", ""), field._name));
                        else
                            SourceBox.Items.Add(new ListItem(field._description.Replace("<br/>", ""), field._name));
                        //-->end
                    }
                }
                else
                {
                    if (this._SearchEntity.SearchField.IndexOf(field._name.ToLower()) >= 0)
                        TargetBox.Items.Add(new ListItem(field._description.Replace("<br/>", ""), field._name));
                    else
                        SourceBox.Items.Add(new ListItem(field._description.Replace("<br/>", ""), field._name));
                }
            }
            this.ddlColumn1.Items.Insert(0, new ListItem("Please Select", String.Empty));
            this.ddlColumn2.Items.Insert(0, new ListItem("Please Select", String.Empty));
            this.ddlColumn3.Items.Insert(0, new ListItem("Please Select", String.Empty));

            // operator
            IList operators = new ArrayList();
            operators.Add(new ListItem("contain", "contain"));
            operators.Add(new ListItem("=", "="));
            operators.Add(new ListItem("!=", "<>"));
            operators.Add(new ListItem(">", ">"));
            operators.Add(new ListItem("<", "<"));
            operators.Add(new ListItem(">=", ">="));
            operators.Add(new ListItem("<=", "<="));

            this.ddlOperator1.DataSource = operators;
            this.ddlOperator1.DataValueField = "Value";
            this.ddlOperator1.DataTextField = "Text";
            this.ddlOperator1.DataBind();

            this.ddlOperator2.DataSource = operators;
            this.ddlOperator2.DataValueField = "Value";
            this.ddlOperator2.DataTextField = "Text";
            this.ddlOperator2.DataBind();

            this.ddlOperator3.DataSource = operators;
            this.ddlOperator3.DataValueField = "Value";
            this.ddlOperator3.DataTextField = "Text";
            this.ddlOperator3.DataBind();

            //status
            //if (this._SearchType != "AP")
            if (this.searchFlowType != "AP")
            {
                BEGDC.CC.BL.Common.IUtility iutility = AppContainer.Instance[ServiceConst.UtilityService] as BEGDC.CC.BL.Common.IUtility;
                IList statuses = iutility.GetState();
                for (int i = 0; i < statuses.Count; i++)
                {
                    if (((State)statuses[i]).StateCode == "Drawback")
                    {
                        statuses.RemoveAt(i);
                        i--;
                    }
                }

                this.ddlStatus1.DataSource = statuses;
                this.ddlStatus1.DataValueField = "StateCode";
                this.ddlStatus1.DataTextField = "StateCode";
                this.ddlStatus1.DataBind();
                this.ddlStatus1.Items.Insert(0, new ListItem("PleaseSelect", String.Empty));

                this.ddlStatus2.DataSource = statuses;
                this.ddlStatus2.DataValueField = "StateCode";
                this.ddlStatus2.DataTextField = "StateCode";
                this.ddlStatus2.DataBind();
                this.ddlStatus2.Items.Insert(0, new ListItem("PleaseSelect", String.Empty));

                this.ddlStatus3.DataSource = statuses;
                this.ddlStatus3.DataValueField = "StateCode";
                this.ddlStatus3.DataTextField = "StateCode";
                this.ddlStatus3.DataBind();
                this.ddlStatus3.Items.Insert(0, new ListItem("PleaseSelect", String.Empty));
            }
            else
            {
                this.ddlStatus1.Items.Add(new ListItem("PleaseSelect", String.Empty));
                this.ddlStatus1.Items.Add(new ListItem("Open", "Open"));
                this.ddlStatus1.Items.Add(new ListItem("Close", "Close"));

                this.ddlStatus2.Items.Add(new ListItem("PleaseSelect", String.Empty));
                this.ddlStatus2.Items.Add(new ListItem("Open", "Open"));
                this.ddlStatus2.Items.Add(new ListItem("Closed", "Close"));

                this.ddlStatus3.Items.Add(new ListItem("PleaseSelect", String.Empty));
                this.ddlStatus3.Items.Add(new ListItem("Open", "Open"));
                this.ddlStatus3.Items.Add(new ListItem("Close", "Close"));
            }


            // logic
            IList logic = new ArrayList();

            logic.Add(new ListItem("", String.Empty));
            logic.Add(new ListItem("And", "and"));
            logic.Add(new ListItem("Or", "or"));

            this.ddlLogic1.DataSource = logic;
            this.ddlLogic1.DataValueField = "Value";
            this.ddlLogic1.DataTextField = "Text";
            this.ddlLogic1.DataBind();

            this.ddlLogic2.DataSource = logic;
            this.ddlLogic2.DataValueField = "Value";
            this.ddlLogic2.DataTextField = "Text";
            this.ddlLogic2.DataBind();

            this._SearchType = searchType;
            this._SearchResult = null;

            #region Setting Province Category Cluster Company Executive
            //if (this._SearchType == "EV")
            if (this.searchFlowType == "EV")
            {
                //Province
                BEGDC.CC.BL.Common.IUtility iutility = AppContainer.Instance[ServiceConst.UtilityService] as BEGDC.CC.BL.Common.IUtility;
                DataTable provinces = iutility.GetProvinces();

                this.ddlProvince1.DataSource = provinces.DefaultView;
                this.ddlProvince1.DataValueField = "Name";
                this.ddlProvince1.DataTextField = "Name";
                this.ddlProvince1.DataBind();
                this.ddlProvince1.Items.Insert(0, new ListItem("PleaseSelect", String.Empty));

                this.ddlProvince2.DataSource = provinces.DefaultView;
                this.ddlProvince2.DataValueField = "Name";
                this.ddlProvince2.DataTextField = "Name";
                this.ddlProvince2.DataBind();
                this.ddlProvince2.Items.Insert(0, new ListItem("PleaseSelect", String.Empty));

                this.ddlProvince3.DataSource = provinces.DefaultView;
                this.ddlProvince3.DataValueField = "Name";
                this.ddlProvince3.DataTextField = "Name";
                this.ddlProvince3.DataBind();
                this.ddlProvince3.Items.Insert(0, new ListItem("PleaseSelect", String.Empty));

                //Category
                DataTable categories = iutility.GetCategories();
                this.ddlCategory1.DataSource = categories.DefaultView;
                this.ddlCategory1.DataValueField = "Name";
                this.ddlCategory1.DataTextField = "Name";
                this.ddlCategory1.DataBind();
                this.ddlCategory1.Items.Insert(0, new ListItem("PleaseSelect", String.Empty));

                this.ddlCategory2.DataSource = categories.DefaultView;
                this.ddlCategory2.DataValueField = "Name";
                this.ddlCategory2.DataTextField = "Name";
                this.ddlCategory2.DataBind();
                this.ddlCategory2.Items.Insert(0, new ListItem("PleaseSelect", String.Empty));

                this.ddlCategory3.DataSource = categories.DefaultView;
                this.ddlCategory3.DataValueField = "Name";
                this.ddlCategory3.DataTextField = "Name";
                this.ddlCategory3.DataBind();
                this.ddlCategory3.Items.Insert(0, new ListItem("PleaseSelect", String.Empty));

                //Cluster
                DataTable clusteres = iutility.GetClusters();
                this.ddlCluster1.DataSource = clusteres.DefaultView;
                this.ddlCluster1.DataValueField = "Name";
                this.ddlCluster1.DataTextField = "Name";
                this.ddlCluster1.DataBind();
                this.ddlCluster1.Items.Insert(0, new ListItem("PleaseSelect", String.Empty));

                this.ddlCluster2.DataSource = clusteres.DefaultView;
                this.ddlCluster2.DataValueField = "Name";
                this.ddlCluster2.DataTextField = "Name";
                this.ddlCluster2.DataBind();
                this.ddlCluster2.Items.Insert(0, new ListItem("PleaseSelect", String.Empty));

                this.ddlCluster3.DataSource = clusteres.DefaultView;
                this.ddlCluster3.DataValueField = "Name";
                this.ddlCluster3.DataTextField = "Name";
                this.ddlCluster3.DataBind();
                this.ddlCluster3.Items.Insert(0, new ListItem("PleaseSelect", String.Empty));

                //Company Executive
                DataTable executives = iutility.GetExecutives();
                this.ddlExecutive1.DataSource = executives.DefaultView;
                this.ddlExecutive1.DataValueField = "NameEN";
                this.ddlExecutive1.DataTextField = "NameEN";
                this.ddlExecutive1.DataBind();
                this.ddlExecutive1.Items.Insert(0, new ListItem("PleaseSelect", String.Empty));

                this.ddlExecutive2.DataSource = executives.DefaultView;
                this.ddlExecutive2.DataValueField = "NameEN";
                this.ddlExecutive2.DataTextField = "NameEN";
                this.ddlExecutive2.DataBind();
                this.ddlExecutive2.Items.Insert(0, new ListItem("PleaseSelect", String.Empty));

                this.ddlExecutive3.DataSource = executives.DefaultView;
                this.ddlExecutive3.DataValueField = "NameEN";
                this.ddlExecutive3.DataTextField = "NameEN";
                this.ddlExecutive3.DataBind();
                this.ddlExecutive3.Items.Insert(0, new ListItem("PleaseSelect", String.Empty));
            }
            #endregion

            if (this._SearchID > 0)
                this.SetEditValue();

        }
        #endregion

        #region Search data

        /// <summary>
        /// Sample:
        /// <Conditions>
        /// <Condition1 field="" operation="=" value="" join="and"></Condition1>
        /// <Condition2 field="" operation="=" value="" join="and"></Condition2>
        /// <Condition3 field="" operation="=" value="" join="and"></Condition3>
        /// </Conditions>
        /// </summary>
        private void SetEditValue()
        {
            if (this._SearchEntity.SearchCondition == string.Empty)
                return;

            System.Xml.XmlDocument xmldoc = new System.Xml.XmlDocument();
            xmldoc.LoadXml(this._SearchEntity.SearchCondition);

            System.Xml.XmlElement xmlCond1 = xmldoc.DocumentElement["Condition1"];
            if (xmlCond1 != null)
            {
                if (xmlCond1.Attributes["field"].Value != string.Empty)
                {
                    this.ddlColumn1.SelectedValue = xmlCond1.Attributes["field"].Value;
                    this.ddlOperator1.SelectedValue = xmlCond1.Attributes["operation"].Value;
                    this.ddlLogic1.SelectedValue = xmlCond1.Attributes["join"].Value;

                    if (ddlColumn1.SelectedValue == "Status")
                        this.ddlStatus1.SelectedValue = xmlCond1.Attributes["value"].Value;
                    else
                        this.txtValue1.Text = xmlCond1.Attributes["value"].Value;
                }
            }

            System.Xml.XmlElement xmlCond2 = xmldoc.DocumentElement["Condition2"];
            if (xmlCond2 != null)
            {
                if (xmlCond2.Attributes["field"].Value != string.Empty)
                {
                    this.ddlColumn2.SelectedValue = xmlCond2.Attributes["field"].Value;
                    this.ddlOperator2.SelectedValue = xmlCond2.Attributes["operation"].Value;
                    this.ddlLogic2.SelectedValue = xmlCond2.Attributes["join"].Value;

                    if (ddlColumn2.SelectedValue == "Status")
                        this.ddlStatus2.SelectedValue = xmlCond2.Attributes["value"].Value;
                    else
                        this.txtValue2.Text = xmlCond2.Attributes["value"].Value;
                }
            }

            System.Xml.XmlElement xmlCond3 = xmldoc.DocumentElement["Condition3"];
            if (xmlCond3 != null)
            {
                if (xmlCond3.Attributes["field"].Value != string.Empty)
                {
                    this.ddlColumn3.SelectedValue = xmlCond3.Attributes["field"].Value;
                    this.ddlOperator3.SelectedValue = xmlCond3.Attributes["operation"].Value;

                    if (ddlColumn3.SelectedValue == "Status")
                        this.ddlStatus3.SelectedValue = xmlCond3.Attributes["value"].Value;
                    else
                        this.txtValue3.Text = xmlCond3.Attributes["value"].Value;
                }
            }

        }

        private void AppendSqlCondition(ref string xmlCondition, int iIndex, ref string sql, string col, string op, string val)
        {
            if (val.Trim() == String.Empty) return;

            if (op == "contain") sql += " " + col + " like " + "'%" + val + "%'";
            else sql += " " + col + " " + op + "'" + val + "'";

            xmlCondition += string.Format("<Condition{0} field=\"{1}\" operation=\"{2}\" value=\"{3}\" join=\"{4}\"></Condition{5}>", iIndex.ToString(), col, op, val, "{4}", iIndex.ToString());
        }

        private void AppendSqlCondition(ref string xmlCondition, int iIndex, ref string sql, string col, string op, string val, string andor)
        {
            if (val.Trim() == String.Empty) return;
            if (andor == String.Empty) return;

            sql += " " + andor + " ";

            if (op == "contain") sql += " " + col + " like " + "'%" + val + "%'";
            else sql += " " + col + " " + op + "'" + val + "'";

            xmlCondition += string.Format("<Condition{0} field=\"{1}\" operation=\"{2}\" value=\"{3}\" join=\"{4}\"></Condition{5}>", iIndex.ToString(), col, op, val, "{4}", iIndex.ToString());
        }


        private bool IsNumeric(string val)
        {
            bool isNum;
            double retNum;
            isNum = Double.TryParse(val, System.Globalization.NumberStyles.Any, System.Globalization.NumberFormatInfo.InvariantInfo, out retNum);
            return isNum;
        }

        private bool IsDate(string val)
        {
            bool ret = false;
            try
            {
                System.DateTime.Parse(val);
                ret = true;
            }
            catch
            { }

            return ret;

        }


        private string FetchSQL()
        {
            //obtain query string
            string sql = "";
            string col, op, val, andor = "";

            string xmlCondition = string.Empty;

            //sql = string.Format(" RoleName in ({0}) or EmployeeNo = '{1}' ", ((BEGDC.CC.BL.Workflow.CCPrincipal)HttpContext.Current.User).Roles, ((BEGDC.CC.BL.Workflow.CCIdentity)HttpContext.Current.User.Identity).UserInfo.Id);
            #region ---- get the query string --
            if (this.ddlColumn1.SelectedIndex > 0)
            {
                col = this.ddlColumn1.SelectedValue;
                op = this.ddlOperator1.SelectedValue;

                val = String.Empty;
                if (this.ddlColumn1.SelectedValue == "Bransh" || this.ddlColumn1.SelectedValue == "Cluster" || this.ddlColumn1.SelectedValue == "CAT" || this.ddlColumn1.SelectedValue == "CompanyExecutive")
                {
                    op = "=";
                    if (this.ddlColumn1.SelectedValue == "Bransh")
                    {
                        if (this.ddlProvince1.SelectedIndex > 0)
                            val = this.ddlProvince1.SelectedValue;
                    }
                    if (this.ddlColumn1.SelectedValue == "Cluster")
                    {
                        if (this.ddlCluster1.SelectedIndex > 0)
                            val = this.ddlCluster1.SelectedValue;
                    }
                    if (this.ddlColumn1.SelectedValue == "CAT")
                    {
                        if (this.ddlCategory1.SelectedIndex > 0)
                            val = this.ddlCategory1.SelectedValue;
                    }
                    if (this.ddlColumn1.SelectedValue == "CompanyExecutive")
                    {
                        if (this.ddlExecutive1.SelectedIndex > 0)
                            val = this.ddlExecutive1.SelectedValue;
                    }
                }
                else
                {
                    if (this.ddlColumn1.SelectedValue == "Status")
                    {
                        op = "=";
                        if (this.ddlStatus1.SelectedIndex > 0)
                            val = this.ddlStatus1.SelectedValue;
                    }
                    else if (this.ddlColumn1.SelectedValue.Contains("Date"))
                    {
                        val = this.txtTime1.Text.Trim();
                    }
                    else
                    {
                        val = PageSafeHelper.SafeText(this.txtValue1.Text.Trim());
                    }
                }

                andor = String.Empty;

                if (((SearchField)(this._SearchFields[col]))._datatype == "Int")
                {
                    if (!IsNumeric(val))
                    {
                        Page.RegisterClientScriptBlock("", "<script>alert(\"" + String.Format(BEGDC.CC.Resource.SystemMessage.SM014, ((SearchField)(this._SearchFields[col]))._description) + "\");</script>");
                        return string.Empty;
                    }
                }

                if (((SearchField)(this._SearchFields[col]))._datatype == "Date")
                {
                    if (!IsDate(val))
                    {
                        Page.RegisterClientScriptBlock("", "<script>alert(\"" + String.Format(BEGDC.CC.Resource.SystemMessage.SM018, ((SearchField)(this._SearchFields[col]))._description) + "\");</script>");
                        return string.Empty;
                    }
                }

                AppendSqlCondition(ref xmlCondition, 1, ref sql, col, op, val, "and");

                andor = this.ddlLogic1.SelectedValue;

                xmlCondition = xmlCondition.Replace("{4}", andor);
            }

            if (this.ddlColumn2.SelectedIndex > 0)
            {
                col = this.ddlColumn2.SelectedValue;
                op = this.ddlOperator2.SelectedValue;

                val = String.Empty;

                if (this.ddlColumn2.SelectedValue == "Bransh" || this.ddlColumn2.SelectedValue == "Cluster" || this.ddlColumn2.SelectedValue == "CAT" || this.ddlColumn2.SelectedValue == "CompanyExecutive")
                {
                    op = "=";
                    if (this.ddlColumn2.SelectedValue == "Bransh")
                    {
                        if (this.ddlProvince2.SelectedIndex > 0)
                            val = this.ddlProvince2.SelectedValue;
                    }
                    if (this.ddlColumn2.SelectedValue == "Cluster")
                    {
                        if (this.ddlCluster2.SelectedIndex > 0)
                            val = this.ddlCluster2.SelectedValue;
                    }
                    if (this.ddlColumn2.SelectedValue == "CAT")
                    {
                        if (this.ddlCategory2.SelectedIndex > 0)
                            val = this.ddlCategory2.SelectedValue;
                    }
                    if (this.ddlColumn2.SelectedValue == "CompanyExecutive")
                    {
                        if (this.ddlExecutive2.SelectedIndex > 0)
                            val = this.ddlExecutive2.SelectedValue;
                    }
                }
                else
                {

                    if (this.ddlColumn2.SelectedValue == "Status")
                    {
                        op = "=";
                        if (this.ddlStatus2.SelectedIndex > 0)
                            val = this.ddlStatus2.SelectedValue;
                    }
                    else if (this.ddlColumn2.SelectedValue.Contains("Date"))
                    {
                        val = this.txtTime2.Text.Trim();
                    }
                    else
                    {
                        val = PageSafeHelper.SafeText(this.txtValue2.Text.Trim());
                    }
                }

                if (((SearchField)(this._SearchFields[col]))._datatype == "Int")
                {
                    if (!IsNumeric(val))
                    {
                        Page.RegisterClientScriptBlock("", "<script>alert('" + String.Format(BEGDC.CC.Resource.SystemMessage.SM014, ((SearchField)(this._SearchFields[col]))._description) + "');</script>");
                        return string.Empty;
                    }
                }

                if (((SearchField)(this._SearchFields[col]))._datatype == "Date")
                {
                    if (!IsDate(val))
                    {
                        Page.RegisterClientScriptBlock("", "<script>alert(\"" + String.Format(BEGDC.CC.Resource.SystemMessage.SM018, ((SearchField)(this._SearchFields[col]))._description) + "\");</script>");
                        return string.Empty;
                    }
                }
                AppendSqlCondition(ref xmlCondition, 2, ref sql, col, op, val, andor);

                andor = this.ddlLogic2.SelectedValue;
                xmlCondition = xmlCondition.Replace("{4}", andor);

            }

            if (this.ddlColumn3.SelectedIndex > 0)
            {
                col = this.ddlColumn3.SelectedValue;
                op = this.ddlOperator3.SelectedValue;

                val = String.Empty;
                if (this.ddlColumn3.SelectedValue == "Bransh" || this.ddlColumn3.SelectedValue == "Cluster" || this.ddlColumn3.SelectedValue == "CAT" || this.ddlColumn3.SelectedValue == "CompanyExecutive")
                {
                    op = "=";
                    if (this.ddlColumn3.SelectedValue == "Bransh")
                    {
                        if (this.ddlProvince3.SelectedIndex > 0)
                            val = this.ddlProvince3.SelectedValue;
                    }
                    if (this.ddlColumn3.SelectedValue == "Cluster")
                    {
                        if (this.ddlCluster3.SelectedIndex > 0)
                            val = this.ddlCluster3.SelectedValue;
                    }
                    if (this.ddlColumn3.SelectedValue == "CAT")
                    {
                        if (this.ddlCategory3.SelectedIndex > 0)
                            val = this.ddlCategory3.SelectedValue;
                    }
                    if (this.ddlColumn3.SelectedValue == "CompanyExecutive")
                    {
                        if (this.ddlExecutive3.SelectedIndex > 0)
                            val = this.ddlExecutive3.SelectedValue;
                    }
                }
                else
                {
                    if (this.ddlColumn3.SelectedValue == "Status")
                    {
                        op = "=";
                        if (this.ddlStatus3.SelectedIndex > 0)
                            val = this.ddlStatus3.SelectedValue;
                    }
                    else if (this.ddlColumn3.SelectedValue.Contains("Date"))
                    {
                        val = this.txtTime3.Text.Trim();
                    }
                    else
                    {
                        val = PageSafeHelper.SafeText(this.txtValue3.Text.Trim());
                    }
                }

                if (((SearchField)(this._SearchFields[col]))._datatype == "Int")
                {
                    if (!IsNumeric(val))
                    {
                        Page.RegisterClientScriptBlock("", "<script>alert('" + String.Format(BEGDC.CC.Resource.SystemMessage.SM014, ((SearchField)(this._SearchFields[col]))._description) + "');</script>");
                        return string.Empty;
                    }
                }
                if (((SearchField)(this._SearchFields[col]))._datatype == "Date")
                {
                    if (!IsDate(val))
                    {
                        Page.RegisterClientScriptBlock("", "<script>alert(\"" + String.Format(BEGDC.CC.Resource.SystemMessage.SM018, ((SearchField)(this._SearchFields[col]))._description) + "\");</script>");
                        return string.Empty;
                    }
                }

                AppendSqlCondition(ref xmlCondition, 3, ref sql, col, op, val, andor);
                xmlCondition = xmlCondition.Replace("{4}", string.Empty);

            }

            if (sql != string.Empty)
                sql = sql.Substring(0, 4) + " (" + sql.Substring(4) + ")";

            xmlCondition = "<Condition>" + xmlCondition + "</Condition>";
            this._SearchSQL_Condition = xmlCondition;

            string fields = string.Empty;
            foreach (System.Web.UI.WebControls.ListItem field in this.TargetBox.Items)
            {
                if (fields != string.Empty)
                    fields += ", ";
                fields += field.Value;
            }

            fields = fields.ToLower();

            if (searchFlowType != "AP")
            {
                if (fields.IndexOf("appid") < 0)
                {
                    if (fields == string.Empty)
                        fields += "appid";
                    else
                        fields += " ,appid";
                }
                if (fields.IndexOf("flowid") < 0)
                    fields += " ,flowid";
                if (fields.IndexOf("currentactivestepname") < 0)
                    fields += " ,currentactivestepname";
                if (fields.IndexOf("status") < 0)
                    fields += " ,status";
                if (fields.IndexOf("type") < 0)
                    fields += " ,type";

                this._SearchSQL_Fields = fields;

                if (((BEGDC.CC.BL.Workflow.CCPrincipal)Page.User).IsLeader)
                {
                    if (sql.Trim() == string.Empty)
                        sql = "SELECT DISTINCT   " + fields + " FROM  vw_ApplicationDetail_" + searchFlowType + "  " + sql;
                    else
                        sql = "SELECT DISTINCT   " + fields + " FROM  vw_ApplicationDetail_" + searchFlowType + " Where " + sql.Substring(4);
                }
                else
                {
                    if (searchFlowType == SEARCH_OCV || searchFlowType == SEARCH_OCR || searchFlowType == SEARCH_EBDCV || searchFlowType == SEARCH_EBD || searchFlowType == SEARCH_ESCCV || searchFlowType == SEARCH_EBD)
                    {
                        BEGDC.CC.BL.UserManagement.IUser iuser = BEGDC.Utility.Castle.AppContainer.Instance[BEGDC.CC.BL.Common.ServiceConst.UserService] as BEGDC.CC.BL.UserManagement.IUser;
                        BEGDC.CC.BL.Workflow.CCPrincipal currentUser = Page.User as BEGDC.CC.BL.Workflow.CCPrincipal;
                        if (currentUser.IsInRole(BEGDC.CC.BL.Workflow.UserRole.SSMEHead))
                        {
                            sql = "SELECT DISTINCT   " + fields + " FROM  vw_ApplicationDetail_" + searchFlowType + " Where (CostCenterName is not null)" + sql;
                        }
                        else if (currentUser.IsInRole(BEGDC.CC.BL.Workflow.UserRole.OCRMgr) || currentUser.IsInRole(BEGDC.CC.BL.Workflow.UserRole.OCVMgr)
                            || currentUser.IsInRole(BEGDC.CC.BL.Workflow.UserRole.OCRStaff) || currentUser.IsInRole(BEGDC.CC.BL.Workflow.UserRole.OCVStaff)
                            || currentUser.IsInRole(BEGDC.CC.BL.Workflow.UserRole.EBDCRMgr) || currentUser.IsInRole(BEGDC.CC.BL.Workflow.UserRole.EBDCVMgr)
                            || currentUser.IsInRole(BEGDC.CC.BL.Workflow.UserRole.EBDCRStaff) || currentUser.IsInRole(BEGDC.CC.BL.Workflow.UserRole.EBDCVStaff)
                            || currentUser.IsInRole(BEGDC.CC.BL.Workflow.UserRole.ESCCRMgr) || currentUser.IsInRole(BEGDC.CC.BL.Workflow.UserRole.ESCCVMgr)
                            || currentUser.IsInRole(BEGDC.CC.BL.Workflow.UserRole.ESCCRStaff) || currentUser.IsInRole(BEGDC.CC.BL.Workflow.UserRole.ESCCVStaff))
                        {
                            sql = "SELECT DISTINCT   " + fields + " FROM  vw_ApplicationDetail_" + searchFlowType + " Where (actor='" + ((BEGDC.CC.BL.Workflow.CCIdentity)User.Identity).UserInfo.NameEN + "' Or actor in (" + ((BEGDC.CC.BL.Workflow.CCPrincipal)User).Roles + "))" + sql;
                        }
                        else if (currentUser.IsInRole(BEGDC.CC.BL.Workflow.UserRole.CostCenterHead))
                        {
                            string costcenter = iuser.GetCostCenterByConstCenterHead(((BEGDC.CC.BL.Workflow.CCIdentity)currentUser.Identity).UserInfo.Id);
                            sql = "SELECT DISTINCT   " + fields + " FROM  vw_ApplicationDetail_" + searchFlowType + " Where (CostCenterName='" + costcenter + "')" + sql;
                        }

                        else if (currentUser.IsInRole(BEGDC.CC.BL.Workflow.UserRole.DeptHead))
                        {
                            string contcenters = string.Empty;
                            if (((BEGDC.CC.BL.Workflow.CCIdentity)currentUser.Identity).UserInfo.Department != null)
                            {
                                contcenters = iuser.GetCostCenterByDepartment(((BEGDC.CC.BL.Workflow.CCIdentity)currentUser.Identity).UserInfo.Department.DepartmentCode);
                                contcenters = contcenters.Replace(",", "','");

                            }
                            sql = "SELECT DISTINCT   " + fields + " FROM  vw_ApplicationDetail_" + searchFlowType + " Where (Department='" + ((BEGDC.CC.BL.Workflow.CCIdentity)currentUser.Identity).UserInfo.Department.DepartmentCode + "' or CostCenterName in ('" + contcenters + "'))" + sql;
                        }
                        else
                        {
                            sql = "SELECT DISTINCT   " + fields + " FROM  vw_ApplicationDetail_" + searchFlowType + " Where (actor='" + ((BEGDC.CC.BL.Workflow.CCIdentity)User.Identity).UserInfo.NameEN + "' Or actor in (" + ((BEGDC.CC.BL.Workflow.CCPrincipal)User).Roles + "))" + sql;
                        }
                    }
                    else
                    {
                        //role2 table: 10007 CODDirector
                        if (((CSPrincipal)User).Role2s.Contains("10007") && (searchFlowType == WorkflowTypes.EV || searchFlowType == WorkflowTypes.CR))
                        {
                            if (sql.Trim() == string.Empty)
                                sql = "SELECT DISTINCT   " + fields + " FROM  vw_ApplicationDetail_" + searchFlowType;
                            else
                                sql = "SELECT DISTINCT   " + fields + " FROM  vw_ApplicationDetail_" + searchFlowType + " Where 1=1 " + sql;
                        }
                        else
                        {
                            sql = "SELECT DISTINCT   " + fields + " FROM  vw_ApplicationDetail_" + searchFlowType + " Where (actor='" + ((BEGDC.CC.BL.Workflow.CCIdentity)User.Identity).UserInfo.NameEN + "' Or actor in (" + ((BEGDC.CC.BL.Workflow.CCPrincipal)User).Roles + "))" + sql;
                        }
                    }
                }
            }
            else
            {
                if (fields == string.Empty)
                    fields += " apid, meetingid ";
                else
                    fields += ",apid, meetingid ";

                this._SearchSQL_Fields = fields;

                if (((BEGDC.CC.BL.Workflow.CCPrincipal)Page.User).IsLeader)
                {
                    if (sql.Trim() == string.Empty)
                        sql = "SELECT DISTINCT   " + fields + " FROM  vw_ApplicationDetail_" + searchFlowType + " " + sql;
                    else
                        sql = "SELECT DISTINCT   " + fields + " FROM  vw_ApplicationDetail_" + searchFlowType + " where " + sql.Substring(4);
                }
                else
                {
                    sql = "SELECT DISTINCT   " + fields + " FROM  vw_ApplicationDetail_" + searchFlowType + " Where (actor='" + ((BEGDC.CC.BL.Workflow.CCIdentity)User.Identity).UserInfo.NameEN + "' Or actor in (" + ((BEGDC.CC.BL.Workflow.CCPrincipal)User).Roles + "))" + sql;

                }
            }

            //this._SearchSQL_Condition = sql;

            //sql = "  CurrentActiveOwner in (" + ((CCPrincipal)HttpContext.Current.User).Roles + ")"  + sql;
            if (sql.ToUpper().IndexOf("WHERE") >= 0)
                sql += " and status <> 'Deleted'";
            else
                sql += " where status <> 'Deleted'";

            return sql;

            //			// read DB
            //			DataTable result = null;

            //			BEGDC.CC.BL.AdvancedSearch.IAdvancedSearch iquery = AppContainer.Instance[BEGDC.CC.BL.Common.ServiceConst.SearchService] as  BEGDC.CC.BL.AdvancedSearch.IAdvancedSearch;
            //
            //			try
            //			{
            //				result = iquery.QueryList( sql );
            //			}
            //			catch
            //			{
            //			}

            //			if( result != null )
            //			{
            //                foreach( DataRow row in result.Rows )
            //				{
            //					if ( row["ChangeStatus"] != System.DBNull.Value )
            //					{
            //						row["ChangeStatus"] = BEGDC.CC.Resource.Workflow.Keys.GetString( row["ChangeStatus"].ToString() );
            //					}
            //				}
            //			}

            //			return result;
        }


            #endregion
        #endregion

        #region FormatDateString
        protected string FormatDateString(object dateStr)
        {
            if (dateStr == DBNull.Value || dateStr == null) return "";

            return UserControls.WebUtility.FormatDateString(Convert.ToDateTime(dateStr));
        }
        #endregion

        //===================================== events ===============================		
        void btnSaveSearch_Click(object sender, EventArgs e)
        {
            //Page.RegisterClientScriptBlock("","<script>window.parent.leftFrame.location='../left.aspx?item=1';</script>");
            if (!this.Panel1.Visible) return;
            this._SearchSQL = string.Empty;

            BindData(1);

            this.Panel1.Visible = true;
        }

        void btnExport_Click(object sender, EventArgs e)
        {
            this.dgTaskList.AllowPaging = false;
            this.BindData(1);

            //if (this._SearchType == SEARCH_OCR || this._SearchType == SEARCH_OCV || this._SearchType == SEARCH_EBD || this._SearchType == SEARCH_ESC || this._SearchType == SEARCH_EBDCV || this._SearchType == SEARCH_ESCCV)
            if (this.searchFlowType == SEARCH_OCR || this.searchFlowType == SEARCH_OCV || this.searchFlowType == SEARCH_EBD || this.searchFlowType == SEARCH_ESC || this.searchFlowType == SEARCH_EBDCV || this.searchFlowType == SEARCH_ESCCV)
                BEGDC.CC.Web.Control.ExportDataGridToExcel.ExportWithSum(Page, dgTaskList, "AdvancedSearch.xls", this.lblCostSum.Text);
            else
                BEGDC.CC.Web.Control.ExportDataGridToExcel.Export(Page, dgTaskList, "AdvancedSearch.xls");
        }

        void btnSearch_Click(object sender, EventArgs e)
        {
            this._SearchSQL = string.Empty;

            this.dgTaskList.CurrentPageIndex = 0;

            BindData(1);

            if (this._SearchSQL != string.Empty)
                this.Panel1.Visible = true;
        }

        public void dgTaskList_SortCommand(object source, DataGridSortCommandEventArgs e)
        {
            //			BEGDC.CC.BL.AdvancedSearch.IAdvancedSearch iquery = AppContainer.Instance[ServiceConst.SearchService] as  BEGDC.CC.BL.AdvancedSearch.IAdvancedSearch;


            SortManager sort = this._SortManager;
            sort.DoSort(e.SortExpression);
            //			if (this._SearchSQL == string.Empty)
            //			{
            //				this._SearchSQL = FetchSQL() ;
            //
            //				this._SearchSQL += " order by " + sort;
            //			}

            //			System.Data.DataTable dtSearchs = iquery.QueryList(this._SearchSQL);

            //			int count = dtSearchs.Rows.Count;

            //			this.CreateGridColumn(dtSearchs);

            //SortManager sort = this._SortManager;
            //dtSearchs.DefaultView.Sort = sort.DoSort( e.SortExpression );
            //			this.dgTaskList.DataSource = dtSearchs.DefaultView;
            //			this.dgTaskList.DataBind();

            //			SetPageCount(count, 1);

            this._SortManager = sort;

            this._SearchSQL = string.Empty;

            this.BindData(this._CurrentPageIndex);

        }


        private void CreateGridColumn(System.Data.DataTable dtSearchs)
        {
            int i = 0;

            if (this.dgTaskList.Columns.Count > 1) return;

            //if (this._SearchType != "AP")
            if (this.searchFlowType != "AP")
            {
                System.Web.UI.WebControls.BoundColumn newCol = new BoundColumn();

                newCol.DataField = "appid";
                newCol.ReadOnly = true;
                newCol.Visible = false;

                this.dgTaskList.Columns.AddAt(0, newCol);

                newCol = new BoundColumn();

                newCol.DataField = "flowid";
                newCol.ReadOnly = true;
                newCol.Visible = false;

                this.dgTaskList.Columns.AddAt(1, newCol);

                i = 2;
            }
            else
            {
                System.Web.UI.WebControls.BoundColumn newCol = new BoundColumn();

                newCol.DataField = "apid";
                newCol.ReadOnly = true;
                newCol.Visible = false;

                this.dgTaskList.Columns.AddAt(0, newCol);

                newCol = new BoundColumn();

                newCol.DataField = "meetingid";
                newCol.ReadOnly = true;
                newCol.Visible = false;

                this.dgTaskList.Columns.AddAt(1, newCol);

                i = 2;
            }

            bool isOnlyShowPCAT = false;

            foreach (System.Data.DataColumn col in dtSearchs.Columns)
            {
                if (col.ColumnName.ToLower() == "appid" || col.ColumnName.ToLower() == "flowid" || col.ColumnName.ToLower() == "currentactivestepname" || col.ColumnName.ToLower() == "type" || col.ColumnName.ToLower() == "apid" || col.ColumnName.ToLower() == "meetingid")
                    continue;
                if ((col.ColumnName.ToLower() == "bransh" || col.ColumnName.ToLower() == "cat") && isOnlyShowPCAT && this.searchFlowType == BEGDC.CC.BL.Workflow.FlowTypes.EV.ToString())
                    continue;

                System.Web.UI.WebControls.BoundColumn newCol = new BoundColumn();
                newCol.HeaderText = (col.ColumnName.ToLower() == "bransh" || col.ColumnName.ToLower() == "cat") ? "Province(CAT) <br/> 省份(运行商)" : GetCaption(col.ColumnName);
                newCol.DataField = col.ColumnName;
                newCol.ReadOnly = true;
                newCol.DataFormatString = GetDataFormatString(col.ColumnName);
                newCol.Visible = true;
                newCol.SortExpression = col.ColumnName;

                if (col.ColumnName.ToLower() == "bransh" || col.ColumnName.ToLower() == "cat") isOnlyShowPCAT = true;

                this.dgTaskList.Columns.AddAt(i, newCol);

                i++;
            }
        }

        private string GetDataFormatString(string fieldname)
        {
            foreach (SearchField field in this._SearchFields.Values)
            {
                if (field._name.ToLower() == fieldname.ToLower())
                    if (field._datatype == "Date")
                        return "{0:M/d/yyyy}";
            }
            return string.Empty;
        }

        private string GetCaption(string fieldname)
        {
            foreach (SearchField field in this._SearchFields.Values)
            {
                if (field._name.ToLower() == fieldname.ToLower())
                    return field._description;
            }
            return fieldname;
        }

        private void BindData(int pageIndex)
        {
            BEGDC.CC.BL.AdvancedSearch.IAdvancedSearch iquery = AppContainer.Instance[ServiceConst.SearchService] as BEGDC.CC.BL.AdvancedSearch.IAdvancedSearch;

            if (this._SearchSQL == string.Empty)
            {
                string sql = FetchSQL();

                if (sql == string.Empty)
                    return;
                this._SearchSQL = sql;


                SortManager sort = this._SortManager;
                if (sort.ToString() != string.Empty)
                    this._SearchSQL += " order by " + sort.ToString();

            }

            System.Data.DataTable dtSearchs = iquery.QueryList(this._SearchSQL);

            int count = dtSearchs.Rows.Count;

            this.CreateGridColumn(dtSearchs);

            //OCO total cost
            //if (this._SearchType == SEARCH_OCR || this._SearchType == SEARCH_OCV || this._SearchType == SEARCH_EBD || this._SearchType == SEARCH_ESC || this._SearchType == SEARCH_EBDCV || this._SearchType == SEARCH_ESCCV)
            if (searchFlowType == SEARCH_OCR || searchFlowType == SEARCH_OCV || searchFlowType == SEARCH_EBD || searchFlowType == SEARCH_ESC || searchFlowType == SEARCH_EBDCV || searchFlowType == SEARCH_ESCCV)
            {
                bool hasBudget = false;
                bool hasActualCost = false;

                double budget = 0;
                double actualCost = 0;
                if (this._SearchSQL_Fields.IndexOf("Budget".ToLower()) > -1)
                {
                    hasBudget = true;
                }

                if (this._SearchSQL_Fields.IndexOf("ActualCost".ToLower()) > -1)
                {
                    hasActualCost = true;
                }

                if (hasBudget || hasActualCost)
                {
                    this.Panel2.Visible = true;
                    foreach (System.Data.DataRow objDR in dtSearchs.Rows)
                    {
                        if (hasBudget)
                        {
                            if (objDR["Budget"] != System.DBNull.Value)
                            {
                                budget = budget + Convert.ToDouble(objDR["Budget"]);
                            }
                        }
                        if (hasActualCost)
                        {
                            if (objDR["ActualCost"] != System.DBNull.Value)
                            {
                                actualCost = actualCost + Convert.ToDouble(objDR["ActualCost"]);
                            }
                        }
                    }

                    if (hasBudget)
                    {
                        this.lblCostSum.Text = "Total Budget (总预算): " + budget.ToString() + "\r\n";
                    }
                    if (hasActualCost)
                        this.lblCostSum.Text = this.lblCostSum.Text + "         	Total Actual Cost (实际总花费): " + actualCost.ToString();
                }
                else
                    this.Panel2.Visible = false;
            }

            this.dgTaskList.DataSource = dtSearchs.DefaultView;
            this.dgTaskList.DataBind();

            //this.dgTaskList.SortCommand += new System.Web.UI.WebControls.DataGridSortCommandEventHandler(this.dgTaskList_SortCommand);

            SetPageCount(count, pageIndex);


        }

        private void GetSearchFields()
        {
            string filename = this.Request.PhysicalApplicationPath + "\\advancesearch.xml";
            if (System.IO.File.Exists(filename))
            {
                System.IO.TextReader tr = System.IO.File.OpenText(filename);
                string xml = tr.ReadToEnd();

                tr.Close();

                System.Xml.XmlDocument xmlDoc = new System.Xml.XmlDocument();
                xmlDoc.LoadXml(xml);

                System.Collections.Hashtable htFields = new Hashtable();
                System.Collections.ArrayList arKeys = new ArrayList();

                foreach (System.Xml.XmlNode element in xmlDoc["advanceSearch"].ChildNodes)
                {
                    //if (element.Attributes["name"].Value == this._SearchType)
                    if (element.Attributes["name"].Value == this.searchFlowType)
                    {
                        foreach (System.Xml.XmlNode elementField in element.ChildNodes)
                        {
                            SearchField field = new SearchField();
                            field._name = elementField.Attributes["name"].Value;
                            field._description = elementField.Attributes["description"].Value;
                            field._isdefault = Convert.ToBoolean(elementField.Attributes["isdefault"].Value);
                            field._issearch = Convert.ToBoolean(elementField.Attributes["issearch"].Value);
                            field._datatype = elementField.Attributes["datatype"].Value; ;
                            htFields.Add(field._name, field);
                            arKeys.Add(field._name);
                        }
                    }
                }
                this._SearchFields = htFields;
                this._SearchFieldsKey = arKeys;
            }

        }

        private void dgTaskList_ItemDataBound(object source, System.Web.UI.WebControls.DataGridItemEventArgs e)
        {

            try
            {
                if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
                {
                    string url = string.Empty;
                    //if (this._SearchType != "AP")
                    if (this.searchFlowType != "AP")
                    {
                        string appid = e.Item.Cells[0].Text;
                        string flowid = e.Item.Cells[1].Text;

                        //url = string.Format("../workflow/WorkflowView.aspx?appid={0}&flowid={1}&PDType={2}&State=View&Type=App", appid, flowid, this._SearchType);
                        url = string.Format("../workflow/WorkflowView.aspx?appid={0}&flowid={1}&PDType={2}&State=View&Type=App", appid, flowid, this.searchFlowType);

                    }
                    else
                    {
                        string apid = e.Item.Cells[0].Text;
                        string meetingid = e.Item.Cells[1].Text;

                        url = string.Format("../UserControls/EV/ActionPoint.aspx?APID={0}&MeetingID={1}&Status=Readonly", apid, meetingid);

                    }

                    ImageButton iblegal = (ImageButton)e.Item.FindControl("imageAdvancedSearch");

                    iblegal.Attributes.Add("onclick", "javascript:showView('" + url + "');");

                }
            }
            catch (GDCException gdcEx)
            {
                WebUtility.Go2ErrorPage(this.Page, gdcEx.ErrorNumber);
            }
            catch (Exception ex)
            {
                WebUtility.Go2ErrorPage(this.Page, BEGDC.CC.BL.Common.ErrorCode.Other_Exception);
            }
        }

        #region choose list
        private void btnRemove_Click(object sender, System.Web.UI.ImageClickEventArgs e)
        {
            try
            {
                int total = this.TargetBox.Items.Count;
                for (int i = 0; i < total; )
                {
                    ListItem item = this.TargetBox.Items[i];
                    if (item.Selected)
                    {
                        this.SourceBox.Items.Add(item);
                        this.TargetBox.Items.Remove(item);
                        this.SourceBox.SelectedIndex = this.SourceBox.Items.Count - 1;
                        total--;
                    }
                    else
                        i++;
                }
                if (this.Panel1.Visible)
                {
                    this._SearchSQL = string.Empty;
                    this.BindData(1);
                }
            }
            catch (GDCException gdcEx)
            {
                WebUtility.Go2ErrorPage(this.Page, gdcEx.ErrorNumber);
            }
            catch
            {
                WebUtility.Go2ErrorPage(this.Page, BEGDC.CC.BL.Common.ErrorCode.Other_Exception);
            }
        }

        private void btnRemoveAll_Click(object sender, System.Web.UI.ImageClickEventArgs e)
        {
            try
            {
                while (this.TargetBox.Items.Count > 0)
                {
                    ListItem item = this.TargetBox.Items[0];
                    this.SourceBox.Items.Add(item);
                    this.TargetBox.Items.Remove(item);
                }
                if (this.Panel1.Visible)
                {
                    this._SearchSQL = string.Empty;
                    this.BindData(1);
                }
            }
            catch (GDCException gdcEx)
            {
                WebUtility.Go2ErrorPage(this.Page, gdcEx.ErrorNumber);
            }
            catch
            {
                WebUtility.Go2ErrorPage(this.Page, BEGDC.CC.BL.Common.ErrorCode.Other_Exception);
            }
        }

        private void btnAdd_Click(object sender, System.Web.UI.ImageClickEventArgs e)
        {
            try
            {
                int total = this.SourceBox.Items.Count;
                for (int i = 0; i < total; )
                {
                    ListItem item = this.SourceBox.Items[i];
                    if (item.Selected)
                    {
                        this.TargetBox.Items.Add(item);
                        this.SourceBox.Items.Remove(item);
                        this.TargetBox.SelectedIndex = this.TargetBox.Items.Count - 1;
                        total--;
                    }
                    else
                        i++;
                }
                if (this.Panel1.Visible)
                {
                    this._SearchSQL = string.Empty;
                    this.BindData(1);
                }
            }
            catch (GDCException gdcEx)
            {
                WebUtility.Go2ErrorPage(this.Page, gdcEx.ErrorNumber);
            }
            catch
            {
                WebUtility.Go2ErrorPage(this.Page, BEGDC.CC.BL.Common.ErrorCode.Other_Exception);
            }
        }

        private void btnAddAll_Click(object sender, System.Web.UI.ImageClickEventArgs e)
        {
            try
            {
                while (this.SourceBox.Items.Count > 0)
                {
                    ListItem item = this.SourceBox.Items[0];
                    this.TargetBox.Items.Add(item);
                    this.SourceBox.Items.Remove(item);
                }
                if (this.Panel1.Visible)
                {
                    this._SearchSQL = string.Empty;
                    this.BindData(1);
                }
            }
            catch (GDCException gdcEx)
            {
                WebUtility.Go2ErrorPage(this.Page, gdcEx.ErrorNumber);
            }
            catch
            {
                WebUtility.Go2ErrorPage(this.Page, BEGDC.CC.BL.Common.ErrorCode.Other_Exception);
            }
        }

        #region ---------- paging events ----------------
        private void btnPageFirst_Click(object sender, System.Web.UI.ImageClickEventArgs e)
        {
            this.dgTaskList.CurrentPageIndex = 0;
            this.BindData(1);
        }

        private void btnPagePrev_Click(object sender, System.Web.UI.ImageClickEventArgs e)
        {
            if (_CurrentPageIndex == 1) return;
            this.dgTaskList.CurrentPageIndex = _CurrentPageIndex - 2;
            this.BindData(_CurrentPageIndex - 1);
        }

        private void btnPageNext_Click(object sender, System.Web.UI.ImageClickEventArgs e)
        {
            if (_CurrentPageIndex == _PageCount) return;
            this.dgTaskList.CurrentPageIndex = _CurrentPageIndex;
            this.BindData(_CurrentPageIndex + 1);
        }

        private void btnPageLast_Click(object sender, System.Web.UI.ImageClickEventArgs e)
        {
            this.dgTaskList.CurrentPageIndex = _PageCount - 1;
            this.BindData(_PageCount);
        }

        private void btnGotoPage_Click(object sender, System.Web.UI.ImageClickEventArgs e)
        {
            if (this.txtPage.Text == string.Empty)
            {
                this.txtPage.Text = "1";
            }
            int gotopage = 1;
            try
            {
                gotopage = Convert.ToInt32(this.txtPage.Text);
            }
            catch { }
            int currentpage = 0;

            if (gotopage >= _PageCount)
            {
                gotopage = _PageCount;
                currentpage = gotopage - 1;
                if (currentpage < 0) currentpage = 0;
            }
            else if (gotopage <= 0)
            {
                gotopage = 1;
            }
            else
            {
                currentpage = gotopage - 1;
            }

            this.dgTaskList.CurrentPageIndex = currentpage;

            this.BindData(gotopage);

            this.txtPage.Text = string.Empty;
        }

        #endregion

        #region page navigation
        private int _PageCount
        {
            get
            {
                if (ViewState["PageCount"] != null) return (int)ViewState["PageCount"];
                else
                    return 0;
            }
            set
            {
                ViewState["PageCount"] = value;
            }
        }
        private int _CurrentPageIndex
        {
            get
            {
                if (ViewState["CurrentPageIndex"] != null) return (int)ViewState["CurrentPageIndex"];
                else
                    return 0;
            }
            set
            {
                ViewState["CurrentPageIndex"] = value;
            }
        }
        private int _RowCount
        {
            get
            {
                if (ViewState["RowCount"] != null) return (int)ViewState["RowCount"];
                else
                    return 0;
            }
            set
            {
                ViewState["RowCount"] = value;
            }
        }
        private void SetPageNavi(int newPage)
        {
            if (newPage <= 1)
            {
                this.btnPageFirst.ImageUrl = BEGDC.CC.Web.UserControls.WebUtility.Path + "/images/pg_first_inact.gif";
                this.btnPagePrev.ImageUrl = BEGDC.CC.Web.UserControls.WebUtility.Path + "/images/pg_pre_inact.gif";
                this.btnPageFirst.Attributes["disabled"] = "true";
                this.btnPagePrev.Attributes["disabled"] = "true";
            }
            else
            {
                this.btnPageFirst.ImageUrl = BEGDC.CC.Web.UserControls.WebUtility.Path + "/images/pg_first.gif";
                this.btnPagePrev.ImageUrl = BEGDC.CC.Web.UserControls.WebUtility.Path + "/images/pg_pre.gif";
                this.btnPageFirst.Attributes.Remove("disabled");
                this.btnPagePrev.Attributes.Remove("disabled");
            }

            if (newPage >= _PageCount)
            {
                this.btnPageNext.ImageUrl = BEGDC.CC.Web.UserControls.WebUtility.Path + "/images/pg_next_inact.gif";
                this.btnPageLast.ImageUrl = BEGDC.CC.Web.UserControls.WebUtility.Path + "/images/pg_last_inact.gif";
                this.btnPageNext.Attributes["disabled"] = "true";
                this.btnPageLast.Attributes["disabled"] = "true";
            }
            else
            {
                this.btnPageNext.ImageUrl = BEGDC.CC.Web.UserControls.WebUtility.Path + "/images/pg_next.gif";
                this.btnPageLast.ImageUrl = BEGDC.CC.Web.UserControls.WebUtility.Path + "/images/pg_last.gif";
                this.btnPageNext.Attributes.Remove("disabled");
                this.btnPageLast.Attributes.Remove("disabled");
            }

            this.lblCurrentPageIndex.Text = newPage.ToString();
            this.lblPageCount.Text = _PageCount.ToString();
            this.lblRecordCount.Text = _RowCount.ToString();

        }

        private void SetPageCount(int count, int pageIndex)
        {
            if (count > 0)
            {
                _RowCount = count;
                _PageCount = count / this.dgTaskList.PageSize;
                if (count % this.dgTaskList.PageSize > 0) _PageCount++;

                _CurrentPageIndex = pageIndex;
                SetPageNavi(pageIndex);
            }
            else
            {
                _RowCount = count;
                _PageCount = count;
                _CurrentPageIndex = 0;
                SetPageNavi(0);
            }
        }

        #endregion
        #endregion

        //===================================== internal object definition ===============================
        #region SortManager
        [Serializable]
        private struct SortManager
        {
            private string _sortColumn;
            private string _sortDirection;

            public void DoSort(string column, string direction)
            {
                _sortColumn = column;
                _sortDirection = direction;

            }
            public string DoSort(string column)
            {
                column = column.Trim();
                if (column == String.Empty) return String.Empty;

                if (_sortColumn != null && _sortColumn.Equals(column))
                {
                    if (_sortDirection == "DESC") _sortDirection = "ASC";
                    else _sortDirection = "DESC";
                }
                else
                {
                    _sortColumn = column;
                    _sortDirection = "ASC";
                }

                return _sortColumn + " " + _sortDirection;
            }

            public string ToString()
            {
                if (_sortColumn == null)
                    return string.Empty;

                return _sortColumn + " " + _sortDirection;
            }
        }
        #endregion

        #region SearchField
        [Serializable]
        private class SearchField
        {
            public string _name = string.Empty;
            public string _description = string.Empty;
            public bool _isdefault = false;
            public bool _issearch = false;
            public string _datatype = "Str";
            public SearchField()
            {
            }
            public SearchField(string name, string description, bool isdefault, bool issearch, string datatype)
            {
                _name = name;
                _description = description;
                _isdefault = isdefault;
                _issearch = issearch;
                _datatype = datatype;
            }
        }
        #endregion

    }
}
